package wpmp.portal.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import wcommons.httputils.RequestUtils;
import wpmp.portal.service.UserService;
import wpmp.security.client.internal.PmpResourceUtils;
import wpmp.security.client.internal.SecurityUtils;
import wpmp.utils.quickbean.UserPermission;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 11:49:12 AM Dec 5, 2013
 */
@Controller
@RequestMapping("/index.do")
public class IndexController extends BaseController {

	static final String SUCCESS = "login";

	@Autowired
	private UserService service;

	@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
	public String list(HttpServletRequest req, HttpServletResponse resp, ModelMap modelMap) throws Exception {
		final String loginName = SecurityUtils.getLoginNameFromCookie(req);
		final UserPermission userPermission = PmpResourceUtils.getAndSetUserPermission(req);
		// 用户已经登录了，直接跳转至主页面
		if (userPermission != null && StringUtils.equals(loginName, userPermission.getUser().getLoginName())) {

			if (log.isInfoEnabled()) {
				log.info("[" + loginName + "] login from [" + RequestUtils.getRemoteIp(req) + "] successfully");
			}

			resp.sendRedirect("main.do?U=" + System.currentTimeMillis());
			return null;
		}
		modelMap.addAttribute("loginName", StringUtils.trim(loginName));
		return SUCCESS;
	}
}
